$(document).ready(function() {
    InitMap();
});

function getXmlData(base_url) {
    var result=[];
    $.ajax({
        type: "GET",
        url:base_url,
        async: false,
        dataType: "xml",
        success:function(data) {
            //console.log(data);
            $(data).find('markers marker').each(function(){
                //alert(1);
                //var propertyfor = $(this).find('projectname').text();
                
                var projectname = $(this).attr('projectname');
                var streetname = $(this).attr('streetname');
                var latitude = $(this).attr('latitude');
                var longitude = $(this).attr('longitude');
                var propertyfor = $(this).attr('propertyfor');
                var floorarea = $(this).attr('floorarea');
                var askingprice = $(this).attr('askingprice');
                var listing_id = $(this).attr('listing_id');
                var thumbnail = $(this).attr('thumbnail');
                var bedroom = $(this).attr('bedroom');
                var bathroom = $(this).attr('bathroom');
                
                result.push({
                    0 : latitude,
                    1 : longitude,
                    2 : projectname,
                    3 : streetname,
                    4 : propertyfor,
                    5 : floorarea,
                    6 : askingprice,
                    7 : listing_id,
                    8 : thumbnail,
                    9 : bedroom,
                    10 : bathroom
                });
            });
        },
        error: function() {
            alert("Error");
        }
    });
    
    return result;
}

function GetValueForSearchByMap() {
    var mapUrl = "";
    var base_url = siteurl;
    //Set default value for hidden field
    var propertyfor_value = $('#propertyfor_value').val();
    
    mapUrl = base_url + "listingmap/xmlListing?propertyfor="+propertyfor_value;
    
    return mapUrl;
}

function setValueForSearchByMap() {
    $('#propertyfor_value').val($.trim($('input[name=propertyfor]:checked').val()));
}

//When something change by user's action
$('.map input[name=propertyfor]').change(function(){
    LoadMap();
});
    
$('.map #inputLocation').change(function(){
    LoadMap();
});

$('.map #inputType').change(function(){
    LoadMap();
});


$('.map #inputBeds').change(function(){
    LoadMap();
});

$('.map #inputBaths').change(function(){
    LoadMap();
});

function LoadMap() {
    var locations = new Array();
    
    setValueForSearchByMap();
    
    var searchUrl = GetValueForSearchByMap();
    
    locations = getXmlData(searchUrl);
    
    var markers = new Array();
    var latSum = 0;
    var lngSum = 0;
    
    $.each(locations, function(index, location) {
        latSum = location[0];
        lngSum = location[1];
        if(index == 0) {
            return false;
        }
    });
    
    function autoCenter(){
        var limits = new google.maps.LatLngBounds();
        $.each(locations, function (index, marker){
            limits.extend(marker);
        });
        map.fitBounds(limits);
    }
    
    var mapOptions = {
        //we will be center and zoom maker autimatically for google map
        //that's why the center and zoom attributes will be commen
        //center: new google.maps.LatLng(latSum, lngSum),
        //zoom: 14,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        scrollwheel: false
    };

    var map = new google.maps.Map(document.getElementById('map'), mapOptions);
    var bounds = new google.maps.LatLngBounds();

    $.each(locations, function(index, location) {
        var pos = new google.maps.LatLng(location[0], location[1]);
        bounds.extend(pos);

        var marker = new google.maps.Marker({
            position: pos, //new google.maps.LatLng(location[0], location[1]),
            map: map,
            icon: 'http://html.realia.byaviators.com/assets/img/marker-transparent.png'
        });

        var myOptions = {
            content: '<div class="infobox"><div class="image"><img src="'+ location[8] +'" alt=""></div><div class="title"><a href="detail.html?id='+ location[7] +'">'+location[2]+'</a></div><div class="area"><span class="key">Area: </span><span class="value">'+ location[5] +'<sup>2</sup></span></div><div class="bedroom">Bedrooms: '+ location[9] +'</div><div class="bathroom">Bathrooms: '+ location[10] +'</div><div class="link"><a href="detail.html?id='+ location[7] +'">View more</a></div></div>',
            disableAutoPan: false,
            maxWidth: 0,
            pixelOffset: new google.maps.Size(-146, -190),
            zIndex: null,
            closeBoxURL: "",
            infoBoxClearance: new google.maps.Size(1, 1),
            position: pos,
            isHidden: false,
            pane: "floatPane",
            enableEventPropagation: false
        };
        marker.infobox = new InfoBox(myOptions);
        marker.infobox.isOpen = false;

        var myOptions = {
            draggable: true,
            content: '<div class="marker"><div class="marker-inner"></div></div>',
            disableAutoPan: true,
            pixelOffset: new google.maps.Size(-21, -58),
            position: pos,
            closeBoxURL: "",
            isHidden: false,
            //pane: "mapPane",
            enableEventPropagation: true
        };
        marker.marker = new InfoBox(myOptions);
        marker.marker.open(map, marker);
        markers.push(marker);

        google.maps.event.addListener(marker, "click", function (e) {
            var curMarker = this;

            $.each(markers, function (index, marker) {
                // if marker is not the clicked marker, close the marker
                if (marker !== curMarker) {
                    marker.infobox.close();
                    marker.infobox.isOpen = false;
                }
            });


            if(curMarker.infobox.isOpen === false) {
                curMarker.infobox.open(map, this);
                curMarker.infobox.isOpen = true;
                map.panTo(curMarker.getPosition());
            } else {
                curMarker.infobox.close();
                curMarker.infobox.isOpen = false;
            }

        });
        
        map.fitBounds(bounds);
    });
}

function InitMap() {
    google.maps.event.addDomListener(window, 'load', LoadMap);
}